package com.itheima.security;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
     UserService userService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user=userService.findUserByUserName(username);

        if (null==user){
            return null;
        }

        List Authorities =new ArrayList();
        if (CollectionUtil.isNotEmpty(user.getRoles())){
            for (Role role : user.getRoles()) {
                if (CollectionUtil.isNotEmpty(role.getPermissions())){
                    for (Permission permission : role.getPermissions()) {
                        Authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
                    }
                }
            }
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),Authorities);
    }
}
